﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebChatDAL;
using System.Text;

namespace WebChat.User
{
    public partial class Chatter : System.Web.UI.Page
    {
        WebChatDAO dao = new WebChatDAO();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string chatterIdString = this.Request["chatterId"];

                int chatterId;

                if (!Int32.TryParse(chatterIdString, out chatterId))
                {
                    this.LiteralError.Text = "Invalid chatter Id (chatterId must be int).";
                    return;
                }                

                WebChatDAL.Chatter chatter;
                if (!dao.TryGetChatterByChatterId(chatterId, out chatter))
                {
                    this.LiteralError.Text = "Invalid chatter Id (chatterId must be int).";
                    return;
                }

                this.LiteralUserName.Text = chatter.aspnet_Users.UserName;

                this.LiteralFirstName.Text = Server.HtmlEncode(chatter.FirstName);
                this.LiteralLastName.Text = Server.HtmlEncode(chatter.LastName);
                this.LiteralLastActivityDate.Text = chatter.aspnet_Users.aspnet_Membership.LastLoginDate.ToString();
                 

                WebChatDAL.Chatter currentChatter;
                if (!dao.TryGetChatterByUserName(Page.User.Identity.Name, out currentChatter))
                {
                    this.LiteralError.Text = String.Format("User with the username {0} was not found.", Page.User.Identity.Name);
                    return;
                }
                                
                var messages = dao.GetLastNMessagesByChatterIds(currentChatter.ChatterId, chatter.ChatterId, maxMessagesCount: 50);
                messages = messages.OrderBy(m => m.DateTimeSent);
                this.RepeaterMessages.DataSource = messages;
                this.RepeaterMessages.DataBind();

                this.LiteralRoles.Text = ConcatenateRoles(chatter);

                List<int> messageIds = messages.Select(m => m.MessageId).ToList();
                ViewState["messageIds"] = messageIds;
            }
        }

        protected string SafeEval(string propertyName)
        {
            string value = (string)Eval(propertyName);
            string safeValue = Server.HtmlEncode(value);

            return safeValue;
        }

        protected string EvalChatterUserName()
        {
            ChatterToChatterMessage message = (ChatterToChatterMessage)GetDataItem();        

            WebChatDAL.Chatter senderChatter = message.Chatter1;

            if (message.Chatter1.ChatterId != message.SenderChatterId)
            {
                senderChatter = message.Chatter;
            }

            string sender = "You";

            if (senderChatter.aspnet_Users.UserName != Page.User.Identity.Name)
            {
                sender = senderChatter.aspnet_Users.UserName;
            }

            return sender + " said: ";
        }

        protected void ButtonSendMessage_OnClick(object sender, EventArgs args)
        {
            string otherChatterIdString = this.Request["chatterId"];

            int otherChatterId;

            if (!Int32.TryParse(otherChatterIdString, out otherChatterId))
            {
                this.LiteralError.Text = "Invalid chatter Id (chatterId must be int).";
                return;
            }
                        
            WebChatDAL.Chatter otherChatter;
            if (!dao.TryGetChatterByChatterId(otherChatterId, out otherChatter))
            {
                this.LiteralError.Text = "Invalid chatter Id.";
                return;
            }

            string message = this.TextBoxMessage.Text.Trim();

            if (message == "")
            {
                return;
            }

            WebChatDAL.Chatter currentChatter;
            if (!dao.TryGetChatterByUserName(Page.User.Identity.Name, out currentChatter))
            {
                this.LiteralError.Text = String.Format("User with the username {0} was not found.", Page.User.Identity.Name);
                return;
            }

            dao.SendMessage_ChatterToChatter(currentChatter.ChatterId, otherChatter.ChatterId, message);

            this.TextBoxMessage.Text = String.Empty;

            var messages = dao.GetLastNMessagesByChatterIds(currentChatter.ChatterId, otherChatter.ChatterId, maxMessagesCount: 50);
            messages = messages.OrderBy(m => m.DateTimeSent);
            this.RepeaterMessages.DataSource = messages;
            this.RepeaterMessages.DataBind();
        }

        protected string ConcatenateRoles(WebChatDAL.Chatter chatter)
        {
            StringBuilder roles = new StringBuilder();

            if (chatter.aspnet_Users.aspnet_Roles.Count != 0)
            {
                roles.Append(chatter.aspnet_Users.aspnet_Roles.First().RoleName);

                foreach (aspnet_Roles role in chatter.aspnet_Users.aspnet_Roles.Skip(1))
                {
                    roles.Append(", ");
                    roles.Append(role.RoleName);
                }
            }

            return roles.ToString();
        }

        protected void TimerMessages_OnTick(object sender, EventArgs args)
        {
            string chatterIdString = this.Request["chatterId"];

            int chatterId;

            if (!Int32.TryParse(chatterIdString, out chatterId))
            {
                this.LiteralError.Text = "Invalid chatter Id (chatterId must be int).";
                return;
            }
                        
            WebChatDAL.Chatter chatter;
            if (!dao.TryGetChatterByChatterId(chatterId, out chatter))
            {
                this.LiteralError.Text = "Invalid chatter Id.";
                return;
            }

            List<int> messageIdsOld = (List<int>)ViewState["messageIds"];

            WebChatDAL.Chatter currentChatter;
            if (!dao.TryGetChatterByUserName(Page.User.Identity.Name, out currentChatter))
            {
                this.LiteralError.Text = "You are an invalid chatter!!";
                return;
            }

            var messages = dao.GetLastNMessagesByChatterIds(chatterId, currentChatter.ChatterId, 50);
            messages = messages.OrderBy(m => m.DateTimeSent);

            List<int> messageIds = messages.Select(m => m.MessageId).ToList();

            if (messageIds.Except(messageIdsOld).Count() == 0 &&
                messageIdsOld.Except(messageIds).Count() == 0)
            {
                return; // no need to rebind grid view - no new messages
            }

            ViewState["messageIds"] = messageIds;

            this.RepeaterMessages.DataSource = messages;
            this.RepeaterMessages.DataBind();

            this.UpdatePanelMessages.Update();
        }

        protected int currentChatterId = -1;
        protected int CurrentChatterId
        {
            get
            {
                if (this.currentChatterId == -1)
                {
                    WebChatDAL.Chatter chatter;
                    if (dao.TryGetChatterByUserName(Page.User.Identity.Name, out chatter))
                    {
                        this.currentChatterId = chatter.ChatterId;
                    }
                }

                return this.currentChatterId;
            }
        }

        protected bool EvalSenderChatterIdEqualsCurrentChatterId()
        {
            ChatterToChatterMessage message = (ChatterToChatterMessage)GetDataItem();
            return message.SenderChatterId == CurrentChatterId;

        }
    }
}